using CoreManager.API.Common;
using CoreManager.Models.DTOs;
using CoreManager.Services.Roles;
using Microsoft.AspNetCore.Mvc;

namespace CoreManager.API.Controllers
{
    /// <summary>
    /// 角色管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class RoleController : BaseController
    {
        private readonly IRoleService _roleService;
        private readonly ILogger<RoleController> _logger;

        public RoleController(IRoleService roleService, ILogger<RoleController> logger) : base(logger)
        {
            _roleService = roleService;
            _logger = logger;
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetRoles([FromQuery] RoleQueryDto query)
        {
            var result = await _roleService.GetRolesAsync(query);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 根据ID获取角色详情
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetRoleById(int id)
        {
            var result = await _roleService.GetRoleByIdAsync(id);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 创建角色
        /// </summary>
        /// <param name="createDto">创建角色DTO</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateRole([FromBody] CreateRoleDto createDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest("请求参数无效");
            }

            var result = await _roleService.CreateRoleAsync(createDto);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 更新角色
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <param name="updateDto">更新角色DTO</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateRole(int id, [FromBody] UpdateRoleDto updateDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest("请求参数无效");
            }

            var result = await _roleService.UpdateRoleAsync(id, updateDto);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteRole(int id)
        {
            var result = await _roleService.DeleteRoleAsync(id);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 批量删除角色
        /// </summary>
        /// <param name="ids">角色ID列表</param>
        /// <returns></returns>
        [HttpDelete("batch")]
        public async Task<IActionResult> BatchDeleteRoles([FromBody] List<int> ids)
        {
            if (ids == null || !ids.Any())
            {
                return BadRequest("请选择要删除的角色");
            }

            var result = await _roleService.BatchDeleteRolesAsync(ids);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 分配角色权限
        /// </summary>
        /// <param name="assignDto">权限分配DTO</param>
        /// <returns></returns>
        [HttpPost("assign-permissions")]
        public async Task<IActionResult> AssignRolePermissions([FromBody] AssignRolePermissionsDto assignDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest("请求参数无效");
            }

            var result = await _roleService.AssignRolePermissionsAsync(assignDto);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 获取角色的菜单权限
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns></returns>
        [HttpGet("{roleId}/menus")]
        public async Task<IActionResult> GetRoleMenus(int roleId)
        {
            var result = await _roleService.GetRoleMenusAsync(roleId);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 检查角色编码是否存在
        /// </summary>
        /// <param name="roleCode">角色编码</param>
        /// <param name="excludeId">排除的角色ID</param>
        /// <returns></returns>
        [HttpGet("check-code")]
        public async Task<IActionResult> CheckRoleCodeExists([FromQuery] string roleCode, [FromQuery] int? excludeId = null)
        {
            if (string.IsNullOrWhiteSpace(roleCode))
            {
                return BadRequest("角色编码不能为空");
            }

            var result = await _roleService.CheckRoleCodeExistsAsync(roleCode, excludeId);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 更新角色状态
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        [HttpPatch("{id}/status")]
        public async Task<IActionResult> UpdateRoleStatus(int id, [FromBody] int status)
        {
            if (status < 0 || status > 1)
            {
                return BadRequest("状态值无效");
            }

            var result = await _roleService.UpdateRoleStatusAsync(id, status);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }
    }
}
